--
-- @Author:      feilong
-- @DateTime:    2019-12-19 15:05:48
-- @Description: 消息的处理

local skynet = require "skynet"
local Timer = import("Timer")
local reason = require("reason")
local utils = require("utils")
local constant = require("constant")

local table_insert = table.insert
local table_remove = table.remove
local math_random = math.random



local DeskBase = class("DeskBase")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function DeskBase:ctor()

    self.timer = Timer.new()
    self.state_time_handler = nil
end

function DeskBase:register()
    print("________i am DeskBase___")
end

function DeskBase:start()
    self.config = global.config 
    self.user_manager = global.user_manager    
    self.act_id = self.config:getActId()
    self.act_data = self.config:getActivity() --活动配置
end

--状态定时器
function DeskBase:setTimer(time, callback, loop, param)    
    if not time then
        --没设置时间
        dbglog("___定时器没设置时间___")        
        return 
    end 
    if self.state_time_handler then 
        self.timer:unregister(self.state_time_handler)
        self.state_time_handler = nil   
    end
    self.state_time_handler = self.timer:register(time, callback, loop, param)  
end

--关闭定时器
function DeskBase:stopTimer()
    if self.state_time_handler then 
        self.timer:unregister(self.state_time_handler)
        self.state_time_handler = nil   
    end
end

--剩余时间
function DeskBase:getLeftTime()
    local left_time = self.timer:leftTime(self.state_time_handler)
    return left_time
end

--帐单信息
function DeskBase:getBillInfo(user)
    local t = {
        client_version = user:getClientVersion(), --客户端版本
        channel = user:getChannel(), --渠道        
        device_id = user:getDeviceId(), --设备id
    }
    return t
end

--操作玩家金币
function DeskBase:addChip(user, chip, reason)
    if chip == 0 then 
        return 
    end
    local uid = user:getUid()
    local server = R().basesvr({key=uid})
    local ok, succ, ret = server:call('.msg_handler', 'add_coins', uid, chip, reason, self:getBillInfo(user))
    if not ok or not succ then
        errlog(uid,'操作金币失败failed to add coins', ok, succ, chip, user:getCoins(), reason, self:getBillInfo(user))        
        return false
    end    
    user:setCoins(ret.curr)
    self:changeCoin(user, chip, reason)
    return ret.curr
end

--发送消息给redis服务
function DeskBase:sendRedis(uid, cmd, key, field_values)
    field_values = field_values or {}
    local params = self:tableToReds(field_values)
    skynet.send("redis_service", "lua", "sync_cmd", uid, cmd, key, table.unpack(params))
end

function DeskBase:callRedis(uid, cmd, key, field_values)
    field_values = field_values or {}
    local params = self:tableToReds(field_values)
    local result = skynet.call("redis_service", "lua", "sync_cmd", uid, cmd, key, table.unpack(params))
    return self:redisToTable(result)    
end

--redis结果转为table
function DeskBase:redisToTable(res)
    if not res or type(res) ~= "table" then 
        return res
    end
    local data = {}
    for i=1, #res, 2 do
        data[res[i]] = res[i+1]
    end
    return data
end

--table 转成Redis参数
function DeskBase:tableToReds(tb)
    local params = {}
    for k, v in pairs(tb) do            
        if type(v) == "table" then      
            self:tableToReds(v)
        else
            if type(k) ~= "number" then 
                table_insert(params, k)
            end
            table_insert(params, v)
        end
    end
    return params
end

--关闭服务
function DeskBase:stop()
    self:stopTimer()
    skynet.sleep(300)    
    skynet.exit()
end

function DeskBase:makeUserkey(uid)
    return "activity:"..self.act_id..":"..uid
end


--改变桌子状态
function DeskBase:changeState(event)
    self.fsm:fire(event)
end

--当前状态
function DeskBase:getState()
    return self.fsm:get()
end

--状态对应的数字
function DeskBase:getStateNum()
    local state = self:getState()
    for k, v in pairs(self.state_list) do 
        if state == v[1] then 
            return k
        end
    end
    return 0
end

--金币发生改变
function DeskBase:changeCoin(user, chip, money_changed_reason)
    --是否在房间里面
    local uid = user:getUid()
    local coins = user:getCoins()
    local ok,table_gid = R().exdbsvr(1):call('.tlock_mgr','get_player_table',uid)
    dbglog("___activity__changeCoin__coins_____", coins)
    if table_gid and table_gid > 0 then 
        local tsvr_id = utils.extract_table_gid(table_gid)
        R().tablesvr(tsvr_id):send('.table_mgr','update_coins_on_table',uid, table_gid, chip)
    end
    --通知大厅币值改变
    R().hallsvr{key=uid}:send('.msg_handler','toagent', uid, 'notify_money_changed', {coins = coins}, money_changed_reason)
end

--活动时间到后清redis数据
function DeskBase:clearActRedis()
    local key = "act_data_"..self.act_id
    local now = os.time()
    local time = tonumber(self:callRedis(nil, "hget", key) or 0)
    local expire_time = self.config:getEndTime()
    if time < now then --清除数据
        print("clear_act_data=========",time, now)
        self:sendRedis(nil, "del", key)
        self:sendRedis(nil, "hset", key, expire_time)
    end    
end

--发送邮件
function DeskBase:sendAwardMail(award_list)
    local url = constant.ADD_MAIL_URL
    R().hallsvr(1):call('.msg_handler','common_post_data',url,{award_list = award_list})
end

--给玩家发消息
function DeskBase:sendToUser(uid, msg_name, msg)
    R().hallsvr({key=uid}):send('.msg_handler', 'send_msg', uid, msg_name, msg)
end

--参与人数op
function DeskBase:opPartakeNum(uid, mtype)

    local data = {}
    data.uid = uid
    data.type = mtype  
    data.op = "partake_num"
    dbglog("_____opPartakeNum__", dump(data))

    billlog(data)
end










return DeskBase